package module;

import entity.ConfigFile;
import entity.LocalVideoConfig;
import entity.VideoItem;
import lombok.extern.slf4j.Slf4j;
import utils.json.VideoStateUtil;
import utils.json.InitConfig;
import utils.runnable.WebDavUploadRunnable;
import utils.threadpool.ThreadPoolUtil;
import utils.webdav.WebDavTool;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * WebDav功能模块，提供将本地视频上传到WebDav的功能。
 */
@Slf4j
public class WebDav {
    private static final ConfigFile configFile = InitConfig.getInstance().getConfig();
    private static final VideoStateUtil videoStateUtil = VideoStateUtil.getInstance();
    private static final LocalVideoConfig localVideoConfig = videoStateUtil.getLocalVideoConfig();
    private static final ScheduledExecutorService service = ThreadPoolUtil.getInstance().getTimerThreadPool();
    private static final WebDavTool webDavTool = WebDavTool.getInstance();
    private static final String TAG = "WebDav：";

    public static void startWebDav() {
        log.info(InitConfig.WEBDAV_DELAY + "分钟后开始定时将视频上传到云端。任务执行间隔时间：" + InitConfig.PERIOD + "分钟。");
        service.scheduleAtFixedRate(new WebDavTimerTask(), InitConfig.WEBDAV_DELAY, InitConfig.PERIOD, TimeUnit.MINUTES);
    }

    private static class WebDavTimerTask extends TimerTask {

        @Override
        public void run() {
            //每次任务执行前先遍历一遍本地及服务器资源列表，避免重复上传。
            existList();
            log.info(TAG + "开始处理上传WebDav任务。。。");
            List<VideoItem> videos = localVideoConfig.getVideos();
            for (VideoItem item : videos) {
                if (item.getIsWebDav() == 0 && item.getIsDownload() == 2) {
                    File uploadFile = new File(configFile.getYouGet().getDir() + item.getTitle() + ".flv");
                    if (!uploadFile.exists()) {
                        uploadFile = new File(configFile.getYouGet().getDir() + item.getTitle() + ".mp4");
                    }
                    ThreadPoolUtil.getInstance().getWebdavThreadPool().submit(new WebDavUploadRunnable(configFile.getWebdav().getBaseURL(), uploadFile, item));
                    item.setIsWebDav(1);
                }
                try {
                    //每个任务之间间隔5秒。
                    Thread.sleep(5 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            try {
                //线程休眠10秒。给程序充足响应时间。
                Thread.sleep(10 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info(TAG + "上传WebDav任务处理完成。");
        }

        private void existList() {
            List<VideoItem> videos = localVideoConfig.getVideos();
            for (VideoItem item : videos) {
                String webDavPath1 = configFile.getWebdav().getBaseURL() + URLEncoder.encode(item.getTitle(), StandardCharsets.UTF_8) + ".flv";
                String webDavPath2 = configFile.getWebdav().getBaseURL() + URLEncoder.encode(item.getTitle(), StandardCharsets.UTF_8) + ".mp4";
                try {
                    if (webDavTool.existDir(webDavPath1) || webDavTool.existDir(webDavPath2)) {
                        item.setIsWebDav(2);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
